package com.ruoyi.project.tool.swagger;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.deptGate.domain.DeptGate;
import com.ruoyi.project.system.deptGate.service.IDeptGateService;
import com.ruoyi.project.system.face.domain.Face;
import com.ruoyi.project.system.face.service.IFaceService;
import com.ruoyi.project.tool.swagger.domain.IFace;
import com.ruoyi.project.tool.websocket.server.SocketServer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 人脸数据
 * 
 * @author yxb
 * @date 2018-12-04
 */
@Api("人脸数据管理")
@RestController
@RequestMapping("/api/face/")
public class IFaceController extends BaseController {
    @Autowired
    private IFaceService faceService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IDeptGateService gateService;

    @Autowired
    private SocketServer socketServer;

    @ApiOperation("新增人脸数据")
    @Log(title = "人脸数据", businessType = BusinessType.INSERT)
    @PostMapping("save")
    public AjaxResult save(IFace face, @RequestParam("file") MultipartFile file) {
        Face f = new Face();

        if (StringUtils.isBlank(face.getNo()) || StringUtils.isBlank(face.getDeptId() + "") || StringUtils.isBlank(face.getName())) {
            AjaxResult r = AjaxResult.error(1003, "参数不完整");
            r.put("type", Constants.FACE_ADD);
            return r;
        }
        if (StringUtils.isBlank(face.getStatus())) {
            f.setStatus("0");
        } else {
            f.setStatus(face.getStatus());
        }
        if (file != null) {
            // 上传文件，返回文件名
            try {
                String fileName = FileUploadUtils.upload(RuoYiConfig.getFacePath(), file);
                f.setUrl(fileName);
//				Dept dept = deptService.selectDeptById(Long.parseLong(face.getDeptId()));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                AjaxResult r = AjaxResult.error(1009, "文件上传失败");
                r.put("type", Constants.FACE_ADD);
                return r;
            }

            try {
                f.setDeptId(face.getDeptId());
                f.setNo(face.getNo());
                f.setName(face.getName());
                int result = faceService.insertFaceAnon(f);
                if (result > 0) {
                    AjaxResult r = AjaxResult.success();
                    r.put("type", Constants.FACE_ADD);
                    return r;
                } else {
                    AjaxResult r = AjaxResult.error(500, "上传数据失败");
                    r.put("type", Constants.FACE_ADD);
                    return r;
                }
            } catch (Exception e) {
                e.printStackTrace();
                AjaxResult r = AjaxResult.error(500, "上传数据失败");
                r.put("type", Constants.FACE_ADD);
                return r;
            }

        } else {
            AjaxResult r = AjaxResult.error(1003, "文件数据为空");
            r.put("type", Constants.FACE_ADD);
            return r;
        }

    }

    @Deprecated
    @ApiOperation("指定设备开门")
    @Log(title = "控制", businessType = BusinessType.INSERT)
    @PostMapping("openDev")
    public AjaxResult openDev(Integer gateId, Integer deptId) {
        if (StringUtils.isBlank(gateId + "") || StringUtils.isBlank(deptId + "")) {
            return AjaxResult.error(1003, "参数不完整");
        }
        DeptGate gate = new DeptGate();
        gate = gateService.selectDeptGateById(gateId);

        if (gate != null) {
            if (deptId == gate.getDeptId()) {
                if ("1".equals(gate.getStatus())) {
                    return AjaxResult.error(500, "无法连接设备");
                }
                // 打开指定设备，调取开门接口
                boolean status = false;

                if (status) {
                    return AjaxResult.success();
                } else {
                    return AjaxResult.error(500, "通讯失败");
                }

            } else {
                return AjaxResult.error(500, "参数无效");
            }
        } else {
            return AjaxResult.error(500, "参数无效");
        }

    }

    @ApiOperation("指定设备开门")
    @Log(title = "控制", businessType = BusinessType.INSERT)
    @PostMapping("openGate")
    public AjaxResult openGate(String gateId, Integer deptId) {
        if (StringUtils.isBlank(gateId)) {
            return AjaxResult.error(1003, "参数不完整");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", Constants.OPEN_DEV);
        map.put("deptId", null);
        map.put("name", "");
        map.put("no", "");
        map.put("gateId", gateId);
        String strMsg = JSON.toJSONString(map);
        if (socketServer.sessionPool.get(gateId) == null) {
            return AjaxResult.error(500, "通讯失败！");
        }
        socketServer.sendMessage(strMsg, gateId);
        return AjaxResult.success();
    }

    @ApiOperation("获取人脸数据")
    @RequestMapping(value = "queryFaceList", method = RequestMethod.POST)
    public AjaxResult queryFaceList(@RequestParam(value = "deptId", required = false) Integer deptId,
            @RequestParam(value = "version", required = false) Long version) {
        try {
            List<IFace> list = faceService.queryFaceList(deptId, version);
            if (list != null && list.size() > 0) {
                AjaxResult r = AjaxResult.success("获取数据成功");
                String jsonStr = JSON.toJSONString(list);
                r.put("data", jsonStr);
                return r;
            } else {
                return AjaxResult.error(500, "服务器获取数据为空");
            }
        } catch (Exception e) {
            return AjaxResult.error(500, "服务器获取数据失败");
        }
    }

    @RequestMapping(value = "batchAdd", method = RequestMethod.POST)
    public AjaxResult batchAdd() {
        try {
            List<Face> list = faceService.selectFaceList(new Face());
            if (list != null && list.size() > 0) {
                for (int i = 0; i <= 5; i++) {
                    for (Face face : list) {
                        Face model = new Face();
                        model.setName(face.getName() + i);
                        model.setDeptId(face.getDeptId());
                        model.setUrl(face.getUrl());
                        model.setNo(face.getNo());
                        faceService.insertFaceAnon(model);
                    }
                }
            }
            return AjaxResult.success("批量添加成功");
        } catch (Exception e) {
            return AjaxResult.error(500, "服务器获取数据失败");
        }
    }
}
